// pages/apply_refund/apply_refund.js
var common = require("../../common/common.js").common;

var un = require("../../siteinfo.js");

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        array: [ "选择申请原因", "我不想要了", "商品有质量问题", "没有收到货", "商品少发漏发发错", "商品与描述不一致", "质疑假货", "收到商品时有损坏", "其他" ],
        //退货原因
        index1: 0,
        //退货原因索引
        order_pro: [],
        //订单商品
        trade_no: "",
        //订单号
        status: 2,
        //订单状态
        array2: [ "选择售后类型", "退货退款", "我要换货" ],
        //申请售后原因
        scaleArray: [ "选择退款比例", "100%", "95%", "90%", "85%", "80%", "75%", "70%", "65%", "60%", "55%", "50%", "45%", "40%", "35%", "30%", "25%", "20%", "15%", "10%", "5%" ],
        index2: 0,
        //申请售后原因索引,
        scaleIndex: 0,
        imgbox: [],
        //上传的图片
        refund_price: 0,
        //退款金额
        cause_des: "",
        //问题描述
        apply_from: 1,
        //申请来源
        delivery_paid: 0,
        //团长配送费或者运费
        explain: "申请售后前，请先联系客服",
        applyBtn: false,
        //提交按钮是否禁用,
        custom_refund_money: "",
        //自定义退款金额
        after_refund: 0
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        var that = this;
        that.setData({
            trade_no: options.trade_no,
            status: options.type,
            apply_from: options.apply_from,
            apply_status: options.apply_status,
            //1.团员售后 2.团长售后
            domain: app.globalData.domain.slice(0, -10)
        });
        if (options.type == 2) {
            //申请退款
            wx.setNavigationBarTitle({
                title: "申请退款"
            });
            that.setData({
                refundTip: "退款"
            });
        } else if (options.type == 4 || options.type == 127) {
            //申请售后
            that.setData({
                refundTip: "售后"
            });
        }
        this.getBase();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {},
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {
        wx.stopPullDownRefresh();
    },
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {},
    //选择售后类型
    choose_type: function(e) {
        let explain = "";
        let leaderName = this.data.leaderName;
        if (e.detail.value == 1) {
            explain = "如果您买的为水果、生鲜，请先联系客服确认是否需要退货。";
            this.setData({
                custom_refund_money: ""
            });
        } else if (e.detail.value == 2) {
            explain = "请先将收到货物放到" + leaderName + "，平台收到货物审核通过后，会为您补发新的订单。";
            this.setData({
                custom_refund_money: "0.00",
                scaleValue: 0
            });
        }
        let tip = this.data.array2[e.detail.value];
        let array = [];
        let descriptionArr = [];
        if (this.data.after_reason) {
            if (tip == "退货退款") {
                this.data.after_reason.map(x => {
                    if (x.status == 1 && (x.type == 2 || x.type == 4 || x.type == 5)) {
                        array.push(x.reason);
                        descriptionArr.push(x.description);
                    }
                });
            } else if (tip == "我要换货") {
                this.data.after_reason.map(x => {
                    if (x.status == 1 && (x.type == 3 || x.type == 4 || x.type == 5)) {
                        array.push(x.reason);
                        descriptionArr.push(x.description);
                    }
                });
            } else {
                this.data.after_reason.map(x => {
                    if (x.status == 1) {
                        array.push(x.reason);
                        descriptionArr.push(x.description);
                    }
                });
            }
            this.setData({
                array: array,
                descriptionArr: descriptionArr
            });
        }
        this.setData({
            index2: e.detail.value,
            explain: explain,
            index1: 0
        });
    },
    //选择退款比例
    choose_scale: function(e) {
        let scale = this.data.scaleArray[e.detail.value];
        let scaleValue;
        if (scale !== "选择退款比例") {
            scale = Number(scale.split("%")[0]) / 100;
            scaleValue = (this.data.refund_price * scale).toFixed(2);
        } else {
            wx.showModal({
                title: "提示",
                content: "请选择退款比例！"
            });
        }
        this.setData({
            scaleIndex: e.detail.value,
            custom_refund_money: scaleValue
        });
    },
    //选择退货原因
    choose_reason: function(e) {
        if (this.data.descriptionArr[e.detail.value]) {}
        this.setData({
            index1: e.detail.value
        });
    },
    //获取数据
    getData: function() {
        let that = this;
        let trade_no = that.data.trade_no;
        let status = that.data.status;
        let index2 = that.data.index2;
        var array2 = that.data.array2;
        let aftermarket_type;
        if (status == 2) {
            aftermarket_type = 0;
        } else {
            if (array2[index2] == "退货退款") {
                aftermarket_type = 1;
            } else if (array2[index2] == "我要换货") {
                aftermarket_type = 2;
            }
        }
        common.request({
            endpoint: "Order/order_close/orderafter2",
            method: "post",
            data: {
                id: trade_no,
                aftermarket_type: aftermarket_type
            },
            header: {
                "content-type": "application/json"
            },
            success: function(res) {
                var items = res.extra;
                items.pro.refundNum = items.num;
                that.refundMoney(items);
                //计算退款金额
                                that.setData({
                    order_pro: items,
                    delivery_paid: res.extra.delivery_paid,
                    actually_paid: res.extra.actually_paid,
                    item_status: res.extra.items ? res.extra.items[0].status : "",
                    order_status: res.extra.order_status,
                    after_discount_price: res.extra.after_discount_price,
                    refund_img: res.extra.refund_img,
                    return_img: res.extra.return_img,
                    after_reason: res.extra.after_reason ? res.extra.after_reason : ""
                });
                let array = [];
                let descriptionArr = [];
                if (res.extra.after_reason) {
                    if (that.data.status == 2) {
                        res.extra.after_reason.map(x => {
                            if (x.status == 1 && (x.type == 1 || x.type == 5)) {
                                array.push(x.reason);
                                descriptionArr.push(x.description);
                            }
                        });
                    } else {
                        res.extra.after_reason.map(x => {
                            if (x.status == 1) {
                                if (that.data.after_refund == 1) {
                                    //仅退货退款
                                    if (x.type == 2 || x.type == 4 || x.type == 5) {
                                        array.push(x.reason);
                                        descriptionArr.push(x.description);
                                    }
                                } else {
                                    array.push(x.reason);
                                    descriptionArr.push(x.description);
                                }
                            }
                        });
                    }
                    that.setData({
                        array: array,
                        descriptionArr: descriptionArr
                    });
                }
                if (res.extra.order_status != 3) {} else {
                    wx.showModal({
                        title: "订单状态已改变",
                        content: "请重新申请",
                        showCancel: true,
                        cancelText: "取消",
                        cancelColor: "",
                        confirmText: "确定",
                        confirmColor: "",
                        success: function(res) {
                            wx.navigateBack({});
                            if (res.confirm) {}
                        },
                        fail: function(res) {},
                        complete: function(res) {}
                    });
                }
            }
        });
    },
    //选择商品
    select: function(e) {
        let that = this;
        let order_pro = that.data.order_pro;
        let index = e.currentTarget.dataset.index;
        if (order_pro[index].select == 0) {
            order_pro[index].select = 1;
        } else {
            order_pro[index].select = 0;
        }
        //that.clculate(order_pro, that.data.delivery_paid)
                that.setData({
            order_pro: order_pro
        });
    },
    //上传图片
    uploadImage: function() {
        var that = this;
        let imgbox = that.data.imgbox;
        let uniacid;
        if (wx.getStorageSync("uniacid")) {
            uniacid = wx.getStorageSync("uniacid");
        } else {
            uniacid = un.uniacid;
        }
        let domian = app.globalData.domain;
        let len = that.data.imgbox.length;
        let count = 3 - len;
        wx.chooseImage({
            count: count,
            //最多可以选择的图片总数
            sizeType: [ "compressed" ],
            // 可以指定是原图还是压缩图，默认二者都有
            sourceType: [ "album", "camera" ],
            // 可以指定来源是相册还是相机，默认二者都有
            success: function(res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                var tempFilePaths = res.tempFilePaths;
                //启动上传等待中...
                                wx.showLoading({
                    title: "正在上传..."
                });
                var i = 0;
                var length = tempFilePaths.length;
                var upload = function() {
                    wx.uploadFile({
                        url: domian + "Order/order_close/imgfile",
                        filePath: tempFilePaths[i],
                        name: "file",
                        formData: {},
                        header: {
                            "Content-Type": "multipart/form-data",
                            uniacid: wx.getStorageSync("uniacid")
                        },
                        success: function(res) {
                            var data = JSON.parse(res.data);
                            imgbox.push(data.Url);
                            i++;
                            if (i < length) {
                                upload();
                            } else {
                                wx.hideLoading();
                                that.setData({
                                    imgbox: imgbox
                                });
                            }
                        },
                        fail: function(res) {
                            wx.hideToast();
                            wx.showModal({
                                title: "错误提示",
                                content: "上传图片失败",
                                showCancel: false,
                                success: function(res) {}
                            });
                        }
                    });
                };
                upload();
            }
        });
    },
    //删除图片
    delete_img: function(e) {
        let that = this;
        let index = that.data.index;
        let imgbox = that.data.imgbox;
        imgbox.splice(index, 1);
        that.setData({
            imgbox: imgbox
        });
    },
    //计算退款金额
    clculate: function(order_pro, delivery_paid) {
        let that = this;
        let refund_price = 0;
        let status = that.data.status;
        var actually_paid = that.data.actually_paid;
        var chooseNum = 0;
        var order_status = that.data.order_status;
        var proNum = 0;
        that.setData({
            refund_price: refund_price.toFixed(2)
        });
    },
    //保存问题描述
    save_cause: function(e) {
        this.setData({
            cause_des: e.detail.value
        });
    },
    //申请退款
    apply: function(e) {
        let that = this;
        let apply_from = that.data.apply_from;
        let index1 = that.data.index1;
        let array1 = that.data.array;
        let index2 = that.data.index2;
        let array2 = that.data.array2;
        let order_pro = that.data.order_pro;
        let trade_no = that.data.trade_no;
        let imgbox = that.data.imgbox;
        let cause_des = that.data.cause_des;
        let status = that.data.status;
        let refund_img = that.data.refund_img;
        let return_img = that.data.return_img;
        let aftermarket_type;
        if (status == 2 || status == 5) {
            aftermarket_type = 0;
        } else {
            if (array2[index2] == "退货退款") {
                aftermarket_type = 1;
            } else if (array2[index2] == "我要换货") {
                aftermarket_type = 2;
            }
            if (index2 == 0 && that.data.after_refund != 1) {
                wx.showModal({
                    title: "提醒",
                    content: "请选择售后类型",
                    showCancel: false
                });
                //解禁按钮
                                that.setData({
                    applyBtn: false
                });
                return false;
            }
        }
        if (index1 == 0) {
            wx.showModal({
                title: "提醒",
                content: "请选择申请原因",
                showCancel: false
            });
            //解禁按钮
                        that.setData({
                applyBtn: false
            });
            return false;
        }
        //退款金额必须输入
                if (that.data.custom_refund == 1 && that.data.refund_rate_on == 1 && (!that.data.custom_refund_money || parseFloat(that.data.custom_refund_money).toFixed(2) == "0.00" && that.data.index2 != 2)) {
            wx.showModal({
                title: "提示",
                content: "退款金额不能为空或为0!",
                showCancel: false
            });
            return false;
        }
        if (!isNaN(parseFloat(that.data.custom_refund_money)) && parseFloat(that.data.custom_refund_money) > this.data.refund_price) {
            wx.showModal({
                title: "提示",
                content: "退款金额超过范围,请重新输入",
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        that.setData({
                            custom_refund_money: ""
                        });
                    }
                }
            });
            return false;
        }
        if (that.data.custom_refund == 1 && !isNaN(parseFloat(that.data.custom_refund_money)) && parseFloat(that.data.custom_refund_money) > that.data.refund_price) {
            wx.showModal({
                title: "提示",
                content: "退款金额超过范围,请重新输入!",
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        that.setData({
                            refund_money: ""
                        });
                    }
                }
            });
            return false;
        }
        if (that.data.custom_refund == 1 && that.data.refund_rate_on == 2 && that.data.index2 != 2 && that.data.scaleIndex == 0) {
            wx.showModal({
                title: "提示",
                content: "请选择退款比例!",
                showCancel: false,
                success(res) {}
            });
            return false;
        }
        if (!imgbox.length && that.data.status == 2 && refund_img == 1 || !imgbox.length && that.data.status != 2 && return_img == 1) {
            wx.showModal({
                title: "提示",
                content: "请上传凭证图片!",
                showCancel: false
            });
            return false;
        }
        //禁用按钮
                that.setData({
            applyBtn: true
        });
        let item = [];
        for (var i = 0; i < order_pro.length; i++) {
            if (order_pro[i].select == 1) {
                item.push(order_pro[i].item_id);
            }
        }
        let aftermarket_reason = array1[parseInt(index1)];
        if (that.data.item_status == 2) {
            wx.showModal({
                title: "订单状态已改变",
                content: "请重新申请",
                showCancel: true,
                cancelText: "取消",
                cancelColor: "",
                confirmText: "确定",
                confirmColor: "",
                success: function(res) {
                    wx.navigateBack({});
                },
                fail: function(res) {},
                complete: function(res) {}
            });
        } else {
            let scale = that.data.scaleArray[that.data.scaleIndex];
            scale = scale.split("%")[0];
            if (that.data.refund_rate_on == 2 && aftermarket_type == 2) {
                //开通比例换货;
                scale = "0";
            }
            common.request({
                endpoint: "Order/order_close/aftermarket2",
                method: "post",
                data: {
                    aftermarket_type: aftermarket_type,
                    item: trade_no,
                    aftermarket_reason: aftermarket_reason,
                    aftermarket_description: cause_des,
                    openid: wx.getStorageSync("user").openid,
                    file: imgbox,
                    apply_from: apply_from,
                    status: that.data.order_status,
                    num: order_pro.pro.refundNum,
                    custom_refund: that.data.custom_refund,
                    custom_refund_rate: scale,
                    custom_refund_money: that.data.custom_refund_money
                },
                header: {
                    "content-type": "application/json"
                },
                success: function(res) {
                    if (res.code == 1) {
                        //状态改变
                        wx.showModal({
                            title: "订单状态已改变",
                            content: "请重新申请",
                            showCancel: true,
                            cancelText: "取消",
                            cancelColor: "",
                            confirmText: "确定",
                            confirmColor: "",
                            success: function(res) {
                                wx.navigateBack({});
                            },
                            fail: function(res) {},
                            complete: function(res) {}
                        });
                    } else {
                        if (that.data.is_auto_after == 1 && that.data.status == 2) {
                            wx.showToast({
                                title: "申请成功"
                            });
                            setTimeout(() => {
                                wx.reLaunch({
                                    url: "/pages/order/order"
                                });
                            }, 500);
                        } else {
                            wx.showModal({
                                title: "提示",
                                content: "售后问题已提交，人工售后会在24小时内核实处理。",
                                showCancel: false,
                                success: function(res) {
                                    if (apply_from == 1) {
                                        setTimeout(() => {
                                            wx.switchTab({
                                                url: "/pages/order/order"
                                            });
                                        }, 500);
                                    } else {
                                        setTimeout(() => {
                                            wx.reLaunch({
                                                url: "/pagesOrder/pages/member_order/member_order"
                                            });
                                        }, 500);
                                    }
                                }
                            });
                        }
                    }
                },
                fail(err) {
                    wx.showModal({
                        title: "提示",
                        content: err.message,
                        showCancel: false,
                        cancelText: "取消",
                        cancelColor: "",
                        confirmText: "确定",
                        confirmColor: "",
                        success: function(res) {
                            // wx.navigateBack({
                            // })
                            //解禁按钮
                            that.setData({
                                applyBtn: false
                            });
                        },
                        fail: function(res) {},
                        complete: function(res) {}
                    });
                }
            });
        }
    },
    //全局基础配置信息
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                wx.setNavigationBarColor({
                    frontColor: "#ffffff",
                    backgroundColor: res.extra.color_main
                });
                that.setData({
                    is_auto_after: res.extra.is_auto_after,
                    //退款是否自动审核
                    refund_rate_on: res.extra.refund_rate_on,
                    //退款比例还是退款金额
                    refund_count_on: res.extra.refund_count_on,
                    //自定义退款数量
                    custom_refund: res.extra.custom_refund,
                    //自定义退款
                    leader_after: res.extra.leader_after,
                    //团长售后选择 1-退货退款 2-我要换货 3-都有
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    after_refund: res.extra.after_refund
                });
                if (that.data.after_refund == 1) {
                    that.setData({
                        array2: [ "退货退款" ]
                    });
                } else {
                    if (that.data.leader_after == 1 && that.data.apply_status == 2) {
                        that.setData({
                            array2: [ "选择售后类型", "退货退款" ]
                        });
                    } else if (that.data.leader_after == 2 && that.data.apply_status == 2) {
                        that.setData({
                            array2: [ "选择售后类型", "我要换货" ]
                        });
                    } else if (that.data.leader_after == 3 && that.data.apply_status == 2) {
                        that.setData({
                            array2: [ "选择售后类型", "退货退款", "我要换货" ]
                        });
                    }
                }
                //处理模块开关
                                var features = common.getModulesSwich(res.extra.features);
                //处理数据格式
                                that.setData({
                    features: features
                });
                that.getData();
            }
        });
    },
    //加
    add(e) {
        let that = this;
        var order_pro = that.data.order_pro;
        var idx = e.currentTarget.dataset.index;
        if (order_pro.pro.refundNum == order_pro.num) {
            wx.showToast({
                title: "数量已达上限",
                icon: "none"
            });
        } else if (order_pro.pro.refundNum < order_pro.num) {
            order_pro.pro.refundNum++;
        } else {
            wx.showToast({
                title: "数据异常，申请数量超过上限",
                icon: "none"
            });
        }
        that.refundMoney(order_pro);
        //计算退款金额
                that.setData({
            order_pro: order_pro
        });
    },
    //减
    reduce(e) {
        let that = this;
        var order_pro = that.data.order_pro;
        var idx = e.currentTarget.dataset.index;
        if (order_pro.pro.refundNum == 1) {
            wx.showToast({
                title: "申请数量最小为1",
                icon: "none"
            });
        } else if (order_pro.pro.refundNum <= order_pro.num) {
            order_pro.pro.refundNum--;
        } else {
            wx.showToast({
                title: "数据异常，申请数量不能为负值",
                icon: "none"
            });
        }
        that.refundMoney(order_pro);
        //计算退款金额
                that.setData({
            order_pro: order_pro
        });
    },
    recordMoneyValue: function(e) {
        let that = this;
        let value = e.detail.value;
        if (!isNaN(parseFloat(value)) && parseFloat(value) > this.data.refund_price) {
            wx.showModal({
                title: "提示",
                content: "退款金额超过范围,请重新输入",
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        that.setData({
                            custom_refund_money: ""
                        });
                    }
                }
            });
        }
        that.setData({
            custom_refund_money: that.PointNum(value)
        });
    },
    PointNum: function(obj) {
        obj = obj.replace(/[^\d.]/g, "");
        //清除"数字"和"."以外的字符
                obj = obj.replace(/^\./g, "");
        //验证第一个字符是数字
                obj = obj.replace(/\.{2,}/g, ".");
        //只保留第一个, 清除多余的
                obj = obj.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        obj = obj.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
        //只能输入两个小数
                return obj;
    },
    //计算退款金额
    refundMoney(item) {
        var refund_price = item.after_discount_price * item.pro.refundNum == 0 ? "0.00" : (Math.floor((Number(item.after_discount_price) * item.pro.refundNum * 100).toFixed(2)) / 100).toFixed(2);
        this.setData({
            refund_price: refund_price
        });
    }
});